<template>
  <BasicModal 
  v-bind="$attrs"
  :title="isAdd ? '新增' : '编辑'"
  :width="400"
  :loading="loading"
  @ok="onModalConfirm"
  @register="register"
  >
    <Form 
    ref="formRef" 
    :model="formData"
    :rules="roomFormRules"
    :labelCol="{ style: { width: '100px' } }">
      <FormItem label="房间名字" name="name">
        <Input v-model:value="formData.name" />
      </FormItem>
      <FormItem label="价格/小时" name="price">
        <Input v-model:value="formData.price" />
      </FormItem>
      <FormItem label="类型" name="type">
        <Select placeholder="请选择房间类型" v-model:value="formData.type">
          <SelectOption 
          v-for="(item, key) in props.roomTypeOpts" 
          :key="key" 
          :value="item.value">{{ item.label }}</SelectOption>
        </Select>
      </FormItem>
      <FormItem label="状态" name="status">
        <Select placeholder="请选择房间状态" v-model:value="formData.status">
          <SelectOption 
          v-for="item in roomStatusOptions" 
          :key="item.value" 
          :value="item.value">{{ item.label }}</SelectOption>
        </Select>
      </FormItem>
    </Form>
  </BasicModal>
</template>

<script lang="ts" setup>
import { get } from 'lodash-es'
import * as api from '@/api/roomManage'
import { reactive, ref, defineEmits } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { Form, Select, SelectOption, FormItem, Input } from 'ant-design-vue'
import { roomStatusOptions, roomFormRules } from './settings'
import { IDictionaryOpts } from '@/api/dictionary/model'

const formRef = ref();
const loading = ref(false);
const isAdd = ref(true);

const formData = reactive({
  name: '',
  status: '0',
  type: '',
  price: '',
  id: ''
})

const emits = defineEmits<{
  (e: 'confirm', data: any): void
}>()


const props = defineProps<{
  roomTypeOpts?: IDictionaryOpts[]
}>()

const [register] = useModalInner((data) => {
  const modalType = get(data, 'modalType', 'add');

  if (modalType == 'add') {
    isAdd.value = true;
    formRef.value.resetFields();
  } else {
    isAdd.value = false;
    const { name, status, type, price, id } = data;
    formData.id = id;
    formData.name = name;
    formData.type = type;
    formData.price = price;
    formData.status = status;
  }
});


async function onModalConfirm() {
  try {
    loading.value = true;
    const data = await formRef.value.validate();
    if (isAdd.value) {
      data.ordered = false;
      data.useStatus = '1';
      await api.addRoom(data) 
    } else {
      data.id = formData.id;
      await api.editRoom(data);
    }
    loading.value = false;
    emits('confirm', data);
  } catch (err) {
    loading.value = false;
    console.error(err);
  }
}

</script>